package com.yuanchu.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.exception.YuanChuException;
import com.yuanchu.common.utils.DateFormatUtils;
import com.yuanchu.common.utils.PageResult;
import com.yuanchu.store.dto.StoreSettingParamsDto;
import com.yuanchu.store.dao.YoshopStoreSettingDao;
import com.yuanchu.store.dto.EditStoreSettingDto;
import com.yuanchu.store.entity.YoshopExpressEntity;
import com.yuanchu.store.entity.YoshopStoreEntity;
import com.yuanchu.store.entity.YoshopStoreSettingEntity;
import com.yuanchu.store.service.YoshopExpressService;
import com.yuanchu.store.service.YoshopStoreService;
import com.yuanchu.store.service.YoshopStoreSettingService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("yoshopStoreSettingService")
public class YoshopStoreSettingServiceImpl extends ServiceImpl<YoshopStoreSettingDao, YoshopStoreSettingEntity> implements YoshopStoreSettingService {

    @Resource
    private YoshopStoreService storeService;

    @Resource
    private YoshopStoreSettingDao storeSettingDao;
    @Resource
    private YoshopExpressService expressService;

    @Override
    public Map<String, Object> queryData() {

        List<YoshopStoreSettingEntity> list = storeSettingDao.getStoreList();
        Map<String, Object> map = new HashMap<>();
        list.forEach(item -> {
            Map parseObject = JSON.parseObject(item.getValues(), Map.class);
            map.put(item.getKey(), parseObject);
        });
        Map<String, Object> points = new HashMap<>();

        points.put("describe", "a) 积分不可兑现、不可转让,仅可在本平台使用;\\nb) 您在本平台参加特定活动也可使用积分,详细使用规则以具体活动时的规则为准;\\nc) 积分的数值精确到个位(小数点后全部舍弃,不进行四舍五入)\\nd) 买家在完成该笔交易(订单状态为“已签收”)后才能得到此笔交易的相应积分,如购买商品参加店铺其他优惠,则优惠的金额部分不享受积分获取;");
        points.put("points_name", "积分");
        map.put("points", points);
        Map<String, Object> recharge = new HashMap<>();
        recharge.put("describe", "1. 账户充值仅限微信在线方式支付，充值金额实时到账；2. 账户充值套餐赠送的金额即时到账；3. 账户余额有效期：自充值日起至用完即止；4. 若有其它疑问，可拨打客服电话400-000-1234");
        recharge.put("is_custom", 1);
        recharge.put("is_entrance", 1);

        // map.put("recharge", recharge);
        YoshopStoreEntity store = storeService.getById(10001);
        map.put("store", store);
        // Map<String, Object> other = new HashMap<>();
        // other.put("h5Url", "http://8.134.205.222:8001/");
        // map.put("_other", other);
        return map;
    }

    @Override
    public YoshopStoreSettingEntity queryPointData() {
        return this.getOne(new LambdaQueryWrapper<YoshopStoreSettingEntity>().eq(YoshopStoreSettingEntity::getStoreId, 10001).eq(YoshopStoreSettingEntity::getKey, "points"));

    }

    @Override
    public EditStoreSettingDto.StoreSettingForm queryStoreSettingDetail(String key, int storeId) {
        YoshopStoreSettingEntity setting = this.getOne(new QueryWrapper<YoshopStoreSettingEntity>()
                .eq("`key`", key)
                .eq("store_id", storeId));
        if (setting == null) {
            return null;
        }
        return JSON.parseObject(setting.getValues(), EditStoreSettingDto.StoreSettingForm.class);
    }

    @Override
    public boolean updateStoreSetting(EditStoreSettingDto params, int storeId) {
        EditStoreSettingDto.StoreSettingForm form = params.getForm();
        YoshopStoreSettingEntity setting = this.getOne(new QueryWrapper<YoshopStoreSettingEntity>()
                .eq("`key`", params.getKey())
                .eq("store_id", storeId));
        if (setting == null) {
            return false;
        }
        setting.setValues(JSON.toJSONString(form));
        return this.updateById(setting);

    }

    @Override
    public List<YoshopExpressEntity> queryExpressAll(Integer storeId) {
        List<YoshopExpressEntity> entities = expressService.list(new QueryWrapper<YoshopExpressEntity>().eq("store_id", storeId));
        entities.forEach(item -> {
            item.setCreateTime(DateFormatUtils.formatDatetime(item.getCreateTime()));
        });
        return entities;
    }

    @Override
    public void storeSettingInfo(StoreSettingParamsDto param) {
        String key = param.getKey();
        YoshopStoreSettingEntity setting = this.getOne(new QueryWrapper<YoshopStoreSettingEntity>().eq("`key`", key));
        if (setting == null) {
            return;
        }
        if ("recharge".equals(param.getKey())){
            setting.setDescribe("充值设置");
        }else if ("points".equals(param.getKey())){
            setting.setDescribe("积分设置");
        }else if ("register".equals(param.getKey())){
            setting.setDescribe("账户注册设置");
        }else if ("sms".equals(param.getKey())){
            setting.setDescribe("短信通知");
        }else if ("storage".equals(param.getKey())){
            setting.setDescribe("上传设置");
        }else if ("page_category_template".equals(param.getKey())){
            setting.setDescribe("分类页模板");
        }else if ("full_free".equals(param.getKey())){
            setting.setDescribe("满额包邮设置");
        }
        setting.setValues(JSON.toJSONString(param.getForm()));
        setting.setUpdateTime(String.valueOf(Instant.now().toEpochMilli()/1000));

        boolean update = this.updateById(setting);
        if (!update){
            throw new YuanChuException("更新失败");
        }
    }

    @Override
    public StoreSettingParamsDto.SettingForm queryStoreSettingDetail(String key) {
        YoshopStoreSettingEntity setting = this.getOne(new QueryWrapper<YoshopStoreSettingEntity>()
                .eq("`key`", key));
        if (setting == null) {
            return null;
        }
        String values = setting.getValues();
        StoreSettingParamsDto.SettingForm settingForm = JSON.parseObject(values, StoreSettingParamsDto.SettingForm.class);
        return settingForm;
    }

    @Override
    public PageResult<YoshopExpressEntity> queryExpressList(Integer page, String search) {
        LambdaQueryWrapper<YoshopExpressEntity> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(search), YoshopExpressEntity::getExpressName, search);
        Page<YoshopExpressEntity> pageResult = expressService.page(new Page<>(page, 15), lqw);
        List<YoshopExpressEntity> records = pageResult.getRecords();
        records.forEach(item -> {
            item.setCreateTime(DateFormatUtils.formatDatetime(item.getCreateTime()));
        });
        return PageResult.formatPageResult(records, page, 15, pageResult.getTotal());
    }
}